package 字节;

public class 岛屿数量 {
    public static int numIslands(char[][] grid){
        int m=grid.length;
        int n=grid[0].length;
        int res=0;
        for (int i=0;i<m;i++){
            for (int j=0;j<n;j++){
                if(grid[i][j]=='1') res++;
                dfs(i,j,grid);
            }
        }
        return res;
    }

    static void dfs(int a,int b,char[][] grid){
        if(a<0||b<0||a== grid.length||b==grid[0].length) return;
        if(grid[a][b]=='0') return;
        grid[a][b]='0';
        dfs(a-1,b,grid);
        dfs(a+1,b,grid);
        dfs(a,b-1,grid);
        dfs(a,b+1,grid);
    }
    public static void main(String[] args) {
        char[][] grid=
                {{'1','1','1','1','0'},
                        {'0','0','1','1','0'},
                        {'1','0','0','1','0'}};
        System.out.println("numIslands(grid) = " + numIslands(grid));
    }
}
